<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="true"
    :class="{'mobile-el-dialog': showMobilePage}"
    class="open-invoice-common-dialog">
    <div :style="{height:tip?'64px':'46px'}" class="header">
      <el-image :src="tipIcon" class="img"/>
      <div v-if="summary" class="summary">
        <div class="content">{{ summary }}</div>
        <div v-if="tip" class="tip">{{ tip }}</div>
      </div>
    </div>
    <div class="main">
      <img v-if="isSeal" src="../../../assets/hint.png" alt="">
      <el-form
        v-if="!isSeal"
        ref="orderForm"
        :rules="rules"
        label-position="right"
        label-width="80px"
        class="setting-form lineHeight32">
        <el-form-item v-if="isSubmitCost" label="审批人员" prop="userId" style="margin-top: 24px;margin-bottom: 2px;">
          <selectWithUserLoad
            v-if="!receiveDisabled"
            ref="selectOrderOperator"
            :is-no-loading="true"
            :disabled="receiveDisabled"
            :is-submit-cost="isSubmitCost"
            v-model="receiveUsers"
            :default-list="defaultObjectUser || []"
            :extend-params="{
              perPage: 15,
              type: 1,
              authUrl: 'crm:orderList:examine'
            }"
            :collapse-tags="false"
            style="width: 240px;"
            key-name="id"
            label-name="userName"
            multiple
            filterable
            clearable
            @selectDataSave="selectDataSave"
          />
          <span v-else>{{ receiveUsers }}</span>
        </el-form-item>
        <el-form-item v-if="!isSubmitCost && isSendMsg" label="接收人" prop="userId">
          <selectWithUserLoad
            v-if="!receiveDisabled"
            ref="selectOrderOperator"
            :disabled="receiveDisabled"
            v-model="receiveUsers"
            :default-list="defaultObjectUser || []"
            :extend-params="{
              type: 1,
              ...loadUserParams
            }"
            :collapse-tags="false"
            key-name="id"
            label-name="userName"
            style="width: 240px;"
            value-type="object"
            multiple
            filterable
            clearable
          />
          <div v-else-if="defaultObjectUser">
            <el-tag v-for="(item,index) in defaultObjectUser" :key="index" style="height: 25px;line-height: 24px;margin-right:5px;padding: 0 7px;">{{ item.userName }}</el-tag>
          </div>
        </el-form-item>
        <el-form-item v-if="isSendMsg" label="任务描述" prop="content" style="margin-bottom: 10px;">
          <el-input
            :rows="4"
            v-model="dingTalkMsg"
            resize="none"
            style="font-size: 13px;"
            type="textarea"
            maxlength="100"
            placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item v-if="isInvite" label="邀请链接" style="margin-bottom: 10px;">
          <div style="display: flex;">
            <ToolTip :content="inviteUrl" style="max-width: calc(100% - 40px);" />
            <el-button type="text" size="small" @click="handleCopy">复制</el-button>
          </div>
        </el-form-item>
        <el-form-item v-if="isShowSendMsg" label-width="0px" label="" prop="userId">
          <div style="margin-left: 80px">
            <el-checkbox v-model="isSendMsg"><span :style="{fontWeight:isSendMsg?'bold':'normal'}" style="color: #333333;">发送飞书通知</span></el-checkbox>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn-container">
      <el-button :loading="loading" type="primary ok" size="small" style="margin-right:6px" @click="handelOK()">{{ btn1 }}</el-button>
      <el-button class="cancel-btn-style" type="info" size="small" @click="handleClose">{{ btn2 }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getDepartmentUser } from '@/api/auth';
import { allDeptlist } from '@/api/select';
import { handelDepartmentData, getDepartmentTreePath } from '@/utils';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import ElMessage from '@/utils/message';
import Title from '@/components/Title';
import { mapState } from 'vuex';
// icon
import tipIcon from '@/assets/project/tip.png';
export default {
  components: { Title, selectWithUserLoad },
  props: {
    title: {
      type: String,
      default: ''
    },
    btn1: {
      type: String,
      default: ''
    },
    btn2: {
      type: String,
      default: ''
    },
    summary: {
      type: String,
      default: ''
    },
    requestDept: {
      type: Boolean,
      default: false
    },
    status: {
      type: Number,
      default: 1
    },
    allDeptList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    tip: {
      type: String,
      default: ''
    },
    inviteUrl: {
      type: String,
      default: ''
    },
    isInvite: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tipIcon,
      loading: false,
      dialogVisible: false,
      isSubmitCost: false,
      rules: {},
      callbackFun: null,
      isSendMsg: true,
      receiveUsers: [],
      dingTalkMsg: '',
      extendParams: null,
      receiveDisabled: false,
      deptList: [],
      allCascaderProps: {
        multiple: true,
        value: 'id',
        label: 'value'
      },
      defaultObjectUser: [],
      cascaderProps: {
        multiple: true,
        lazy: true,
        value: 'id',
        label: 'value',
        lazyLoad(node, resolve) {
          const { level } = node;
          if (level < 2 && !node.root && node.data) {
            const params = { id: node.data.id };
            getDepartmentUser(params).then(res => {
              handelDepartmentData(res.data);
              resolve(res.data);
            });
          } else {
            resolve();
          }
        }
      },
      selectDataList: '',
      isSeal: false, // 为true则待封账的撤回弹窗不展示表单
      loadUserParams: {}

    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    deptListOption: {
      get: function() {
        if (!this.requestDept) {
          return this.allDeptList;
        } else {
          return this.deptList;
        }
      }
    },
    isShowSendMsg() {
      return !this.isInvite;
    }
  },
  created() {
    if (this.requestDept) {
      // this.getAllDeptList();
    }
  },
  methods: {
    handleClose() {
      // this.receiveUsers = [];
      // this.isSendMsg = false;
      // this.dingTalkMsg = '';
      this.dialogVisible = false;
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    showDialog({ defaultMsg, defaultUser, isSubmitCost, extendParams, defaultObjectUser, receiveDisabled, isSeal, loadUserParams }) {
      this.isSubmitCost = isSubmitCost || false;
      this.loadUserParams = loadUserParams || {};
      this.isSeal = isSeal || false;
      const selectDataList = localStorage.getItem('selectDataList') ? JSON.parse(localStorage.getItem('selectDataList')) : '';
      this.selectDataList = localStorage.getItem('selectDataList');
      if (this.isSubmitCost && selectDataList) {
        this.receiveUsers = selectDataList;
        this.defaultObjectUser = selectDataList;
      } else {
        this.receiveUsers = [];
      }
      this.extendParams = extendParams || null;
      this.receiveDisabled = receiveDisabled || false;
      if (defaultUser) {
        // this.receiveUsers = this.setUserDefault(defaultUser);
        this.receiveUsers = defaultUser;
      }
      if (defaultObjectUser) {
        const list = _.uniqBy(defaultObjectUser, 'id');
        this.defaultObjectUser = list;
        this.receiveUsers = list;
      }
      this.dingTalkMsg = defaultMsg || '';
      this.dialogVisible = true;
    },
    handleCopy() {
      this.$copyText(this.inviteUrl).then(() => {
        this.$message.success('复制成功');
      }, e => {
        console.error(e);
      });
    },
    setUserDefault(defaultUserId) {
      if (defaultUserId.length) {
        const userIds = [];
        for (let i = 0; i < this.deptListOption.length; i++) {
          const item = getDepartmentTreePath(this.deptListOption[i]);
          for (let d = 0; d < item.length; d++) {
            const itemD = item[d];
            const itemLength = itemD.length === 0 ? 0 : itemD.length;
            const lastItem = itemD[itemLength - 1];
            if (defaultUserId.indexOf(lastItem) >= 0) {
              userIds.push(itemD);
            }
          }
        }
        return userIds;
      } else {
        return [];
      }
    },
    handelOK() {
      this.loading = true;
      if (!this.isSeal) {
        if (this.isSubmitCost && this.receiveUsers.length === 0) {
          ElMessage.error('请选择审批人员');
          this.loading = false;
          return;
        }
        if (this.isSendMsg && (this.receiveUsers.length === 0 || this.dingTalkMsg === '')) {
          ElMessage.error('请填写接收人和任务描述');
          this.loading = false;
          return;
        }
      }
      // let userIds = [];
      // if (this.receiveUsers.length > 0) {
      //   userIds = this.receiveUsers.map(i => {
      //     if (i.length > 1) return i[i.length - 1];
      //   }).filter(i => !!i);
      // }
      let ids = [];
      if (this.receiveUsers) {
        ids = this.receiveUsers.map(i => i.id);
      }
      const data = {
        isSendMsg: this.isSendMsg,
        receiveUsers: ids.join(','),
        dingTalkMsg: this.dingTalkMsg,
        url: this.isInvite ? this.inviteUrl : `${location.origin}?redirect=${this.$route.path}`,
        users: this.receiveUsers
      };
      if (this.extendParams)Object.assign(data, this.extendParams);
      if (this.status === 0) data.status = 0;
      if (this.isSubmitCost) {
        localStorage.setItem('selectDataList', this.selectDataList);
        this.$emit('handelOK', data, this.selectDataList);
      } else {
        this.$emit('handelOK', data);
      }
      this.handleClose();
    },
    getAllDeptList() {
      allDeptlist().then(res => {
        handelDepartmentData(res.data);
        this.deptList = res.data;
      });
    },
    selectDataSave(val) {
      this.selectDataList = val;
    }
  }
};
</script>

<style lang="scss" scoped>
.open-invoice-common-dialog{
  &::v-deep {
    .el-dialog{
      position:absolute;
      top:50%;
      left:50%;
      transform:translate(-50%,-50%);
      width: 380px;
      border-radius: 8px;
      margin: 0 !important;
    }
    .el-dialog__header{
      margin: 0;
      padding: 0;
    }
    .el-dialog__body{
      padding: 0;
      margin: 0;
    }
  }
}
.header{
  display: flex;
  width: 100%;
  height: 46px;
  border-radius: 8px 8px 0px 0px;
  align-items: center;
  background: #fff2eb;
  margin-bottom: 17px;
  .img{
    width: 16px;
    height: 18px;
    margin:0 12px 0 24px;
  }
  .summary {
    img {
      display: block;
      margin: 0 auto;
      width: 80px;
      height: 80px;
    }
    .content {
      font-size: 16px;
      font-family: PingFang SC, PingFang SC-Medium;
      font-weight: bold;
      text-align: left;
      color: #333333;
      line-height: 20px;
    }
    .tip{
      font-size: 12px;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      text-align: left;
      line-height: 20px;
      color: #FD8546;
      margin-top: 1px;
    }
  }
}
.main {
  padding: 0 24px;
  img {
    display: block;
    margin: 0 auto;
    width: 80px;
    height: 80px;
  }
  & ::v-deep {
    .el-input {
      width: 240px;
      .el-input__inner {
        width: 240px;
      }
      .el-input__suffix {
        display: flex;
        align-items: center;
      }
    }
    .el-textarea__inner {
      padding: 5px 10px;
      width: 240px;
    }
    .el-tag--info {
      color: #406EFF;
      background-color: #ecf1ff;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
.btn-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  padding-bottom: 29px;
}
</style>
